const menu = document.querySelector(".headerLeft");
const menuIcon = document.querySelector(".headerLeft i");

const search = document.querySelector(".headerRight");
const searchIcon = document.querySelector(".headerRight i");


const mask1 = document.querySelector(".mask1");
const mask2 = document.querySelector(".mask2");

const box1 = document.querySelector('.mask1 .box');

// 获取浏览器可视区域高度(不包含地址栏)(用于懒加载)
const innerHeight = window.innerHeight;

// 页面底部节点 事件委托
const footer = document.querySelector("footer");

// 正常情况下页面底部高度
let footerHeight = 5;

// // 网页可见区域宽 用来协助响应式
let offsetWidth = document.body.offsetWidth;

// token值(用于后台官网的身份识别)
let token;

// 顶部轮播图
let swipeTopArr;
const swipeTopBox=document.querySelector('.swiperTop');
const swipeTopThumbBox=document.querySelector('.thumbsTop');

// 底部轮播图
let swipeBottomArr;
const swipeBottomBox=document.querySelector('.swiperBottom');
const swipeBottomThumbBox=document.querySelector('.thumbsBottom');
let allowRun=true;
// 预加载轮播图
let swipeIndex=0;

// 专门用来缓存图片的节点
let preloadImgNode = document.createElement("img");


window.addEventListener('load',async()=>{
	if(sessionStorage.getItem("tokenKey")&&sessionStorage.getItem("aboutSwipeTopArrKey")){
		token=JSON.parse(sessionStorage.getItem("tokenKey"));
		swipeTopArr=JSON.parse(sessionStorage.getItem('aboutSwipeTopArrKey'));
		// console.log(swipeTopArr);
	}else{
		token = (await _fetch('POST','http://website.bluej.cn/api/admin/login',
				{
		          phone: '18771955164',
		          password: '123456',
		        }
		      )).data.token;
		swipeTopArr=(await _fetch('GET','http://website.bluej.cn/api/carouselGroup/getAllCarouselGroup')).data.rows[5].Carousels;	  
		sessionStorage.setItem("tokenKey", JSON.stringify(token));
		sessionStorage.setItem('aboutSwipeTopArrKey',JSON.stringify(swipeTopArr));
	}
	
	// 图片的缓存 预加载
	while(true){
		if(swipeIndex==swipeTopArr.length){
			swipeIndex=0;
			break;
		}
		await preloadImg();
	}
	
	// // 渲染轮播图
	let swipeTopStr='';
	
	swipeTopArr.forEach((item,index)=>{
		swipeTopStr+=`
		<div class="swiper-slide">
			<img src='${swipeTopArr[index].url}'>
		</div>
		`;
	});
	swipeTopBox.innerHTML=`<div class="swiper-wrapper">${swipeTopStr}</div>`;
	// // 渲染顶部缩略
	swipeTopThumbBox.innerHTML=`<div class="swiper-wrapper">${swipeTopStr}</div>`;
	
	
	let gallerySwiper = new Swiper('.swiperTop',{
	  spaceBetween: 0,
	  thumbs: {
	    swiper: {
	      el: '.thumbsTop',
	      spaceBetween: 10,
	      slidesPerView: 3,
	      watchSlidesVisibility: true,/*避免出现bug*/
	    },
		autoScrollOffset: 1,
	  }
	})
		
})

// 图片的缓存
function preloadImg(){
	return new Promise((resolve,reject)=>{
		preloadImgNode.addEventListener('load',()=>{
			resolve();
		},{once:true});
		// 这里设置{once:true}是为了避免重复监听进而影响性能
		preloadImgNode.src=swipeTopArr[swipeIndex].url;
		swipeIndex++;
	});
}

window.addEventListener('scroll',async()=>{
	//获取页面被卷去高度
	let scrollTop = document.documentElement.scrollTop;
	// console.log(scrollTop);
	// console.log(innerHeight);
	// console.log(swipeBottomBox.getBoundingClientRect().top);
	if(scrollTop+innerHeight>swipeBottomBox.getBoundingClientRect().top&&allowRun){
		// console.log(1);
		allowRun=false;
		if(sessionStorage.getItem("tokenKey")&&sessionStorage.getItem("aboutSwipeBottomArrKey")){
		token=JSON.parse(sessionStorage.getItem("tokenKey"));
		swipeBottomArr=JSON.parse(sessionStorage.getItem('aboutSwipeBottomArrKey'));	
		}else{
			swipeBottomArr=(await _fetch('GET','http://website.bluej.cn/api/carouselGroup/getAllCarouselGroup')).data.rows[6].Carousels;
			sessionStorage.setItem('aboutSwipeBottomArrKey',JSON.stringify(swipeBottomArr));
		}
		// 图片的缓存 预加载
		while(true){
			if(swipeIndex==swipeBottomArr.length){
				swipeIndex=0;
				break;
			}
			await preloadImg();
		}
		let swipeBottomStr='';
		swipeBottomArr.forEach((item,index)=>{
			swipeBottomStr+=`
			<div class="swiper-slide">
				<img src='${swipeBottomArr[index].url}'>
			</div>
			`;
		});
		
		// 渲染底部轮播
		swipeBottomBox.innerHTML=`<div class="swiper-wrapper">${swipeBottomStr}</div>`;
		swipeBottomThumbBox.innerHTML=`<div class="swiper-wrapper">${swipeBottomStr}</div>`;
		// window.removeEventListener('scroll');
		
		let swiperBottom = new Swiper('.swiperBottom',{
		  spaceBetween: 0,
		  thumbs: {
		    swiper: {
		      el: '.thumbsBottom',
		      // spaceBetween: 10,
		      slidesPerView: 3,
		      watchSlidesVisibility: true,/*避免出现bug*/
		    },
			autoScrollOffset: 1,
		  }
		})
	}
});



menu.addEventListener("click", function() {
	if (menuIcon.classList.contains('icon-caidan')) {
		mask1.style.clipPath = "circle(95%)";
		
		menuIcon.style.color = "#d576ba";
		menu.style.background = "#fff";
		menuIcon.classList.remove('icon-caidan');
		menuIcon.classList.add('icon-closel');
		search.style.transform = 'scale(0)';
		mask2.style.transform = 'scale(0)';
	
	} else {
		// mask1.style.clipPath = `circle(${radius}vw at ${positionX}% ${positionY}vw)`;
		mask1.style.clipPath = ``;
		menuIcon.style.color = "#fff";
		menu.style.background = "";
		menuIcon.classList.remove('icon-closel');
		menuIcon.classList.add('icon-caidan');
		search.style.transform = 'scale(1)';
		mask2.style.transform = 'scale(1)';
	}

});

search.addEventListener("click", function() {	
	if (searchIcon.classList.contains('icon-sousuo')) {
		mask2.style.clipPath = "circle(75%)";
		searchIcon.style.color = "#d576ba";
		search.style.background = "#fff";
		searchIcon.classList.remove('icon-sousuo');
		searchIcon.classList.add('icon-closel');
		menu.style.transform = 'scale(0)';
		mask1.style.transform = 'scale(0)';
	} else {
		mask2.style.clipPath = "";
		searchIcon.style.color = "#fff";
		search.style.background = "";
		searchIcon.classList.remove('icon-closel');
		searchIcon.classList.add('icon-sousuo');
		menu.style.transform = 'scale(1)';
		mask1.style.transform = 'scale(1)';
	}
});

footer.addEventListener("click",function(event){
	// 网页可见区域宽 用来协助响应式
	let offsetWidth = document.body.offsetWidth;
	if(offsetWidth<=767){
		footerHeight = 11;
	}else if(offsetWidth<=2339&&offsetWidth>=1025){
		footerHeight = 5;
	}
	
	footerF(event.target.id);
});

// 渲染底部
function footerF(ID){
	
	let footerStr = '';
	switch(ID){
		case 'up':
			footer.style.height = `${footerHeight*2.4}vw`;
			// console.log(footer.style.height)
			footer.style.marginTop = `${-footerHeight*2.4}vw`;
			footer.style.transition = 'all .3s';
			footerStr += `
				<div class="content1">
					<div class="left">
						<h2>Receive the latest Or news and Creativity in our newsletters.</h2>
						<form action="" method="">
							<input type="email" name="" id="login" value="" placeholder='enter address'/>
							<label for="login">Sign Up</label>
						</form>
					</div>
					<div class="right">
						<i class="iconfont icon-xinlangweibo"></i>
						<i class="iconfont icon-weixin"></i>
						<i class="iconfont icon-baidu"></i>
						<i class="iconfont icon-facebookfacebook52"></i>
						<i class="iconfont icon-xiajiantou" id="down"></i>
					</div>
				</div>
				<p>Copyright (c) Nissin Furniture Crafters Co ,Ltd All Rights Reserved</p>
			`;
			footer.innerHTML = footerStr;
		break;
		
		case 'down':
			footer.style.height = `${footerHeight}vw`;
			footer.style.marginTop = `${-footerHeight}vw`;
			footer.style.transition = 'all .3s';
			footerStr += `
				<div class="content">
					<h2>Copyright (c) Nissin Furniture Crafters Co ,Ltd All Rights Reserved</h2>
					<i class="iconfont icon-shangjiantou" id="up"></i>
				</div>
			`;
			footer.innerHTML = footerStr;
		break;
	}
	
}



// 从后台获取数据的方法
async function _fetch(_method, _url, _data) {
  let paramsObj = {
    method: _method,
  };
  // 若使用的方法是get
  if (_method === "GET") {
    paramsObj["headers"] = { "x-token": `${token}` };
    if (_data) {
      _url += "?";
      for (const key in _data) {
        _url += `${key}=${_data[key]}&`;
      }
      _url = _url.slice(0, -1);
    }
  } else {
    paramsObj["headers"] = {
      "Content-type": 'application/json',
    };
    let body = "";
    paramsObj["body"] =JSON.stringify(_data) ;
  }
  
  // console.log(paramsObj);

  let res = await fetch(_url, paramsObj);

  return res.json();
}